# -*- coding: utf-8 -*- 
"""
========================================================================================================================
@project : my-sanic
@file: myLog
@Author: mengying
@email: 652044581@qq.com
@date: 2023/3/3 10:23
@desc: 日志写入模板，可接入第三方日志扩展
========================================================================================================================
"""
import json
import logging
import logging.config as LogConfig
import os
import time
import seqlog
from config import config
from pathlib import PurePath, Path
from typing import AnyStr


class MyLog:
    """日志的基类， 定义文件格式和保存路径等"""

    def __init__(self):
        self.save_path = Path.joinpath(PurePath(__file__).parent.parent, 'logs')
        self.today = time.strftime('%Y-%m-%d')
        os.makedirs(self.save_path, exist_ok=True)

    def get_logger_config(self, filename):
        return {
            'version': 1,
            'formatters': {
                'standard': {
                    'format': '[%(asctime)s] [%(filename)s:%(lineno)d]'
                              '[%(levelname)s]- %(message)s'}
            },
            'handlers': {
                'default': {
                    'level': 'INFO',
                    'class': 'logging.handlers.RotatingFileHandler',
                    'filename': Path.joinpath(self.save_path, '%s-all-%s.log' % (str(filename), self.today)),
                    'maxBytes': 1024 * 1024 * 5,
                    'backupCount': 5,
                    'formatter': 'standard',
                    'encoding': 'utf-8',
                },
                'error': {
                    'level': 'ERROR',
                    'class': 'logging.handlers.RotatingFileHandler',
                    'filename': Path.joinpath(self.save_path, '%s-error-%s.log' % (str(filename), self.today)),
                    'maxBytes': 1024 * 1024 * 5,
                    'backupCount': 5,
                    'formatter': 'standard',
                    'encoding': 'utf-8',
                },
                'console': {
                    'level': 'DEBUG',
                    'class': 'logging.StreamHandler',
                    'formatter': 'standard'
                },
                'info': {
                    'level': 'INFO',
                    'class': 'logging.handlers.RotatingFileHandler',
                    'filename': Path.joinpath(self.save_path, '%s-info-%s.log' % (str(filename), self.today)),
                    'maxBytes': 1024 * 1024 * 5,
                    'backupCount': 5,
                    'formatter': 'standard',
                    'encoding': 'utf-8',
                },

            },
            'loggers': {
                'log': {
                    'handlers': ['error', 'info', 'console', 'default'],
                    'level': 'INFO',
                    'propagate': True
                },
            }
        }

    def get_logger(self, filename=config.PROJECT_NAME):
        LogConfig.dictConfig(self.get_logger_config(filename))
        logger = logging.getLogger("log")
        return logger


class SeqLog(MyLog):
    """seq-log的日志扩展，可以通过配置SEQ_URL和SEQ_KEY 接入seq-log日志平台"""

    def __init__(self, server_url=None, api_key=None):
        self.server_url = server_url or getattr(config, 'SEQ_URL', None)
        self.api_key = api_key or getattr(config, 'SEQ_KEY', None)
        super(SeqLog, self).__init__()

    def get_logger(self, filename=config.PROJECT_NAME):
        if self.api_key and self.server_url:
            seqlog.log_to_seq(
                server_url=self.server_url,
                api_key=self.api_key,
                level=logging.INFO,
                batch_size=20,
                auto_flush_timeout=10,
                override_root_logger=True,
                json_encoder_class=json.encoder.JSONEncoder
            )
        return super().get_logger(filename=filename)


class SimpleLog:
    Logger = None

    @classmethod
    def info(cls, data: AnyStr = None) -> None:
        if cls.Logger is None:
            cls.Logger = MyLog().get_logger()
        cls.Logger.info(str(data))

    @classmethod
    def error(cls, data: AnyStr = None) -> None:
        if cls.Logger is None:
            cls.Logger = MyLog().get_logger()
        cls.Logger.error(str(data))


if __name__ == '__main__':

    # 两种日志模式：logging或者接入三方的seqLog, 使用seqlog一定要配置url和key
    seqLog = SeqLog().get_logger()

    # myLog = MyLog().get_logger()

    for i in range(100000):
        SimpleLog.info("Houston, we have a")
